import axios from 'axios';

// 开发环境使用代理，生产环境使用完整 URL
const BASE_URL = import.meta.env.PROD 
  ? 'https://netdata.aqilmini.com/api/pdf'
  : '/api/pdf';

export interface PDFResponse {
  code: number;
  success: boolean;
  data?: {
    blob?: Blob;
    fileName?: string;
  };
  message?: string;
}

export interface OCRResponse {
  code: number;
  message: string;
  data: {
    text: string;  // 服务器返回的是 { text: string } 格式
  };
}

export interface ConvertResponse {
  code: number;
  message: string;
  data?: {
    blob?: Blob;
    fileName?: string;
  };
}

export interface ImageToPDFResponse {
  code: number;
  message: string;
  data?: {
    blob?: Blob;
    fileName?: string;
  };
}

export interface APIResponse<T> {
  code: number;
  data: T;
}

// 添加错误类型定义
export class APIError extends Error {
  constructor(
    message: string,
    public status?: number,
    public code?: number
  ) {
    super(message);
    this.name = 'APIError';
  }
}

// 添加错误处理函数
const handleAPIError = (error: any): never => {
  if (axios.isAxiosError(error)) {
    const status = error.response?.status;
    const message = error.response?.data?.message;

    switch (status) {
      case 400:
        throw new APIError('请求参数错误', status, 400);
      case 401:
        throw new APIError('未授权，请先登录', status, 401);
      case 403:
        throw new APIError('无权访问该资源', status, 403);
      case 404:
        throw new APIError('请求的资源不存在', status, 404);
      case 413:
        throw new APIError('文件太大，请上传小于50MB的文件', status, 413);
      case 415:
        throw new APIError('不支持的文件类型', status, 415);
      case 422:
        throw new APIError(message || '参数验证失败', status, 422);
      case 429:
        throw new APIError('请求过于频繁，请稍后再试', status, 429);
      case 500:
        throw new APIError('服务器内部错误', status, 500);
      case 502:
        throw new APIError('网关错误', status, 502);
      case 503:
        throw new APIError('服务暂时不可用', status, 503);
      case 504:
        throw new APIError('网关超时', status, 504);
      default:
        throw new APIError(message || '未知错误', status);
    }
  }
  throw new APIError('网络请求失败');
};

export const pdfService = {
  // PDF OCR识别
  async ocrPDF(file: File): Promise<PDFResponse> {
    const formData = new FormData();
    formData.append('file', file);
    const response = await axios.post(`${BASE_URL}/ocr`, formData);
    return response.data;
  },

  // PDF转Word
  async toWord(file: File): Promise<PDFResponse> {
    const formData = new FormData();
    formData.append('file', file);
    const response = await axios.post(`${BASE_URL}/to-word`, formData);
    return response.data;
  },

  // PDF转PPT
  async toPPT(file: File): Promise<PDFResponse> {
    const formData = new FormData();
    formData.append('file', file);
    const response = await axios.post(`${BASE_URL}/to-ppt`, formData);
    return response.data;
  },

  // 图片转PDF
  async imagesToPDF(files: File[]): Promise<void> {
    try {
      const formData = new FormData();
      files.forEach(file => {
        formData.append('files', file);
      });

      const response = await axios.post(
        `${BASE_URL}/images-to-pdf`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          responseType: 'blob',
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total!);
            console.log(`Upload Progress: ${percentCompleted}%`);
          },
        }
      );

      if (response.data instanceof Blob) {
        const blob = new Blob([response.data], { type: 'application/pdf' });
        const fileName = `converted_${new Date().getTime()}.pdf`;
        
        // 直接下载文件
        await this.downloadFile(blob, fileName);
        return;
      }

      throw new APIError('转换失败，返回格式错误');
    } catch (error) {
      throw handleAPIError(error);
    }
  },

  // PDF转换（Word/PPT）
  async convertPDF(file: File, type: 'word' | 'ppt'): Promise<void> {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const endpoint = type === 'word' ? '/to-word' : '/to-ppt';
      const mimeType = type === 'word'
        ? 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        : 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
      const fileExtension = type === 'word' ? 'docx' : 'pptx';

      const response = await axios.post(
        `${BASE_URL}${endpoint}`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          responseType: 'blob'
        }
      );

      if (response.data instanceof Blob) {
        const blob = new Blob([response.data], { type: mimeType });
        const originalName = file.name.replace('.pdf', '');
        const fileName = `${originalName}.${fileExtension}`;
        
        // 直接下载文件
        await this.downloadFile(blob, fileName);
        return;
      }

      throw new APIError('转换失败，返回格式错误');
    } catch (error) {
      throw handleAPIError(error);
    }
  },

  // 合并PDF
  async mergePDFs(files: File[]): Promise<APIResponse<{ blob: Blob; fileName: string }>> {
    const formData = new FormData();
    files.forEach(file => {
      formData.append('files', file);
    });

    try {
      const response = await axios.post(`${BASE_URL}/merge`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        responseType: 'blob'
      });

      return {
        code: 200,
        data: {
          blob: new Blob([response.data], { type: 'application/pdf' }),
          fileName: `merged_${new Date().getTime()}.pdf`
        }
      };
    } catch (error) {
      console.error('Merge PDFs error:', error);
      throw new Error('合并请求失败');
    }
  },

  // 分割PDF
  async splitPDF(file: File, pages: number[]): Promise<PDFResponse> {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('pages', JSON.stringify(pages));

      const response = await axios.post(
        `${BASE_URL}/split`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          responseType: 'blob'
        }
      );

      if (response.data instanceof Blob) {
        const blob = new Blob([response.data], { type: 'application/pdf' });
        const fileName = `split_${new Date().getTime()}.pdf`;

        return {
          code: 200,
          success: true,
          message: 'success',
          data: {
            blob,
            fileName
          }
        };
      }

      throw new Error('Invalid response format');
    } catch (error) {
      throw handleAPIError(error);
    }
  },

  // PDF/图片 OCR识别
  async ocrFile(file: File, lang: string = 'chi_sim+eng'): Promise<OCRResponse> {
    try {
      const formData = new FormData();
      formData.append('file', file);
      
      const response = await axios.post(`${BASE_URL}/ocr`, formData, {
        params: { lang },
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      if (!response.data?.data?.text) {
        throw new APIError('返回数据格式错误');
      }
      
      return response.data;
    } catch (error) {
      throw handleAPIError(error);
    }
  },

  // 文件验证
  validatePDFFile(file: File): boolean {
    // 检查文件类型
    if (file.type !== 'application/pdf' && !file.name.toLowerCase().endsWith('.pdf')) {
      return false;
    }
    
    // 检查文件大小 (50MB)
    const maxSize = 50 * 1024 * 1024;
    if (file.size > maxSize) {
      return false;
    }

    return true;
  },

  // 验证图片文件
  validateImageFile(file: File): boolean {
    // 检查文件类型
    const validTypes = ['image/jpeg', 'image/png', 'image/jpg'];
    if (!validTypes.includes(file.type)) {
      return false;
    }
    
    // 检查单个文件大小 (10MB)
    const maxSize = 10 * 1024 * 1024;
    if (file.size > maxSize) {
      return false;
    }

    return true;
  },

  // 保存文件的方法
  async saveFileWithDialog(blob: Blob, fileName: string): Promise<boolean> {
    try {
      // 创建一个临时的URL
      const url = window.URL.createObjectURL(blob);
      
      // 创建一个临时的a标签
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      link.style.display = 'none';
      
      // 添加到文档中并触发点击
      document.body.appendChild(link);
      link.click();
      
      // 清理
      setTimeout(() => {
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      }, 100);
      
      return true;
    } catch (error) {
      console.error('Save file error:', error);
      throw error;
    }
  },

  // 获取文件扩展名
  getFileExtension(fileName: string): string {
    return fileName.slice(((fileName.lastIndexOf(".") - 1) >>> 0) + 2);
  },

  // 获取文件 MIME 类型
  getMimeType(extension: string): string {
    const mimeTypes = {
      'pdf': 'application/pdf',
      'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
    };
    return mimeTypes[extension as keyof typeof mimeTypes] || 'application/octet-stream';
  },

  // 通用的文件下载方法
  async downloadFile(blob: Blob, fileName: string): Promise<void> {
    try {
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      
      // 添加到文档并触发点击
      document.body.appendChild(link);
      link.click();
      
      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      throw new APIError('下载文件失败，请重试');
    }
  },
}; 